package com.thinkit.cms.service.channel;

import com.thinkit.cms.api.content.ContentService;
import com.thinkit.core.constant.Channel;
import com.thinkit.processor.channel.BaseChannelAdaptService;
import com.thinkit.utils.enums.ChannelEnum;
import com.thinkit.utils.properties.ThinkItProperties;
import com.thinkit.utils.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ContentAllChannelService extends BaseChannelAdaptService implements Cloneable  {

    @Autowired
    ContentService contentService;

    @Autowired
    ThinkItProperties thinkItProperties;

    List<Map<String,Object>> params = new ArrayList<>();

    public void notifyIt(List params){
        this.params = params;
        if(!params.isEmpty()){
            Map<String,Object> map =new HashMap();
            for(int i=0;i<params.size();i++){
                map.put("index_num",i);
                execuate(false,true,map);
            }
        }
    }

    @Override
    protected String loadTempPath() {
        return this.tempPath;
    }

    @Override
    protected String loadDestPath() {
        return this.destPath;
    }

    @Override
    protected Map<String, Object> loadTempParams(Map<String,Object> variable) {
        if(!params.isEmpty()){
            Integer index=(Integer)variable.get("index_num");
            Map<String, Object> ret=  params.get(index);
            Map<String,Object> params = contentService.loadTempParams(ret, Arrays.asList("0","1"));
            setPath(params);
            return params;
        }
        return null;
    }

    public void setPath(Map<String,Object> params){
        if(Checker.BeNotNull(params) && !params.isEmpty()){
            boolean hasTemp=params.containsKey(Channel.TEMP_PATH) && Checker.BeNotNull(params.get(Channel.TEMP_PATH));
            boolean hasDest=params.containsKey(Channel.DEST_PATH) && Checker.BeNotNull(params.get(Channel.DEST_PATH));
            boolean hasPathRule=params.containsKey(Channel.PATH_RULE) && Checker.BeNotNull(params.get(Channel.PATH_RULE));
            if(hasTemp){
                this.tempPath =params.get(Channel.TEMP_PATH).toString();
            }
            if(hasDest){
                String templatePath =thinkItProperties.getSitePath();
                String destPath = params.get(Channel.DEST_PATH).toString();
                String url = params.get(Channel.URL).toString();
                if(hasPathRule){
                    this.destPath = templatePath+destPath+url;
                    params.put(Channel.DEST_PATH,this.destPath);
                }
            }
        }
    }


    @Override
    public ChannelEnum getName() {
        return ChannelEnum.CONTENTS;
    }
}
